package com.gewu.advertisement.core.service

import com.gewu.advertisement.core.common.AuthResult
import com.gewu.advertisement.core.common.HttpClient
import com.gewu.advertisement.core.common.SupervisorLogScope
import com.gewu.advertisement.core.model.ApiResponse
import kotlinx.coroutines.launch
import java.io.IOException

/**
 * @author htt 2021/1/7
 */
class AuthService {
    private val scope = SupervisorLogScope<AuthService>()

    fun auth(
        sn: String,
        appId: String,
        onSuccess: (AuthResult) -> Unit,
        onFail: (Throwable) -> Unit
    ) {
        scope.launch {
            try {
                val url = "http://adp.iot-sys.net/adpServer/device/dev/auth?sn=$sn&appId=$appId"
                val response = HttpClient.get<ApiResponse<AuthResult>>(url)
                if (response.isSuccess) {
                    onSuccess(response.data!!)
                } else {
                    onFail(IOException("认证失败: ${response.msg}"))
                }
            } catch (e: Exception) {
                onFail(e)
            }
        }
    }

}